package com.company;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPServer {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(4603);

        while (true) {

            Socket s = server.accept();
            new Thread(new ThreadServerHandler(s)).start();
        }

    }
}

class ThreadServerHandler implements Runnable{

    private Socket socket;

    public ThreadServerHandler(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();

            while(true) {
                byte[] buf = new byte[1024];
                is.read(buf);
                String s = new String(buf);
                System.out.println("在" + socket.getInetAddress() + ":" + socket.getLocalPort() + "端口接收到信息：" + s);

                Scanner sc = new Scanner(System.in);
                System.out.println("请输入传给客户端的信息：");
                String ans = sc.nextLine();
                byte[] buf2 = ans.getBytes();

                os.write(buf2);
                System.out.println("已向客户端发送信息");
                if(ans.equals("Exit"))
                    break;
            }
            os.close();
            is.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



